<template>
	<view class="fix-top-window">
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="primary" size="mini" @click="add">新增</button>
				<!-- <button class="uni-button" type="warn" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button> -->
				<!-- #ifdef H5 -->
					<!-- <download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
						:type="exportExcel.type" :name="exportExcel.filename">
						<button class="uni-button" type="primary" size="mini">导出 Excel</button>
					</download-excel> -->
				<!-- #endif -->
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" collection="one"
				field="no,name,banji" :where="where" page-data="replace"
				:orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual"
				@load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange"
					class="table-pc">
					<uni-tr>
						<uni-th align="center">学号</uni-th>
						<uni-th align="center">姓名</uni-th>
						<uni-th align="center">班级</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item.no}}</uni-td>
						<uni-td align="center">{{item.name}}</uni-td>
						<uni-td align="center">{{item.banji}}</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button @click="edit(item)" class="uni-button" size="mini"
									type="primary">修改</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<!-- #ifndef MP -->
					<picker class="select-picker" mode="selector" :value="pageSizeIndex" :range="pageSizeOption"
						@change="changeSize">
						<button type="default" size="mini" :plain="true">
							<text>{{pageSizeOption[pageSizeIndex]}} 条/页</text>
							<uni-icons class="select-picker-icon" type="arrowdown" size="12" color="#999"></uni-icons>
						</button>
					</picker>
					<!-- #endif -->
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
			<uni-popup ref="adddlg" type="center" backgroundColor="#fff">
				<view>
					<view class="uni-header">
						<view class="uni-group">
							<view class="uni-title">添加学生</view>
						</view>
					</view>
					<view class="uni-container">
						<uni-forms>
							<uni-forms-item label="学号" labelWidth="85">
								<input class="uni-input-border" type="text" v-model="xh" placeholder="学号"/>
							</uni-forms-item>
							<uni-forms-item label="姓名" abelWidth="85">
								<input class="uni-input-border" type="text" v-model="xm" placeholder="姓名"/>
							</uni-forms-item>
							<uni-forms-item label="班级" labelWidth="85">
								<input class="uni-input-border" type="text" v-model="bj" placeholder="班级"/>
							</uni-forms-item>
							<view class="uni-button-group pointer">
								<button class="uni-button uni-button-full" type="primary" :disabled="isLoading" @click="submitadd">保存</button>
							</view>
						</uni-forms>
					</view>
				</view>
			</uni-popup>
			
			<uni-popup ref="editdlg" type="center" backgroundColor="#fff">
				<view>
					<view class="uni-header">
						<view class="uni-group">
							<view class="uni-title">修改学生</view>
						</view>
					</view>
					<view class="uni-container">
						<uni-forms>
							<uni-forms-item label="id" labelWidth="85">
								<input class="uni-input-border" type="text" disabled="disabled" v-model="editstu._id" />
							</uni-forms-item>
							<uni-forms-item label="学号" labelWidth="85">
								<input class="uni-input-border" type="text" v-model="editstu.no" placeholder="学号"/>
							</uni-forms-item>
							<uni-forms-item label="姓名" abelWidth="85">
								<input class="uni-input-border" type="text" v-model="editstu.name" placeholder="姓名"/>
							</uni-forms-item>
							<uni-forms-item label="班级" labelWidth="85">
								<input class="uni-input-border" type="text" v-model="editstu.banji" placeholder="班级"/>
							</uni-forms-item>
							<view class="uni-button-group pointer">
								<button class="uni-button uni-button-full" type="primary" :disabled="isLoading" @click="submitedit">保存</button>
							</view>
						</uni-forms>
					</view>
				</view>
			</uni-popup>
		</view>
		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '../../js_sdk/validator/uni-id-users.js';

	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '_id desc' // 排序字段
	const dbSearchFields = ['name', 'no', 'banji'] // 支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				editstu:{},
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				pageSizeIndex: 0,
				pageSizeOption: [5, 10, 20, 50],
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"status_localdata": [{
								"text": "正常",
								"value": 0
							},
							{
								"text": "禁用",
								"value": 1
							},
							{
								"text": "审核中",
								"value": 2
							},
							{
								"text": "审核拒绝",
								"value": 3
							}
						]
					},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "uni-id-users.xls",
					"type": "xls",
					"fields": {
						"用户名": "username",
						"手机号码": "mobile",
						"用户状态": "status",
						"邮箱": "email",
						"角色": "role",
						"register_date": "register_date"
					}
				},
				exportExcelData: [],
				noAppidWhatShouldIDoLink: 'https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=makeup-dcloud-appid'
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		watch: {
			pageSizeIndex: {
				immediate: true,
				handler(val, old) {
					this.options.pageSize = this.pageSizeOption[val]
					this.options.pageCurrent = 1
					this.$nextTick(() => {
						this.loadData()
					})
				}
			}
		},
		methods: {
			add(){
				this.$refs.adddlg.open();
			},
			submitadd(){
				uniCloud.callFunction({
					name:"add",
					data:{"stu":{"name":this.xm,"no":this.xh,"banji":this.bj}},
					success(){
						alert("添加成功");
						location.reload();
					}
				})
			},
			edit(m){
				this.editstu = m;
				this.$refs.editdlg.open();
			},
			submitedit(){
				uniCloud.callFunction({
					name:"edit",
					data:{
						"id":this.editstu._id,
						"stu":{"name":this.editstu.name,"no":this.editstu.no,"banji":this.editstu.banji}},
					success(){
						alert("修改成功");
						location.reload();
					}
				})
			},
			onqueryload(data) {
				for (var i = 0; i < data.length; i++) {
					let item = data[i]
					const roleArr = item.role.map(item => item.role_name)
					item.role = roleArr.join('、')
					if (Array.isArray(item.dcloud_appid)) {
						item.dcloud_appid = item.dcloud_appid.join('、')
					}
					item.register_date = this.$formatDate(item.register_date)
				}
				this.exportExcelData = data
			},
			changeSize(e) {
				this.pageSizeIndex = e.detail.value
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				// 下一帧拿到查询条件
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				if(confirm("确定删除吗？")){
					uniCloud.callFunction({
						name:"del",
						data:{"stu":{"_id":id}},
						success(){
							location.reload();
						
						}
					})
				}
				
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			}
		}
	}
</script>

<style>
</style>

		
		<!-- <view>
			学生列表
			<ul>
				<li v-for="(item,index) in arr">
					{{item.name}}
				</li>
			</ul>
			
			<input type="text" v-model="nm" style="border: #007AFF 1px solid;"/>
			<button @click="add">添加</button>
		</view>
		<view>
			<input type="text" v-model="cx" style="border: #007AFF 1px solid;"/>
			<button @click="select">查询</button>
		</view> -->


	// export default {
	// 	data() {
	// 		return {
	// 			arr:[],
	// 			nm:"",
	// 			cx:""
	// 		}
	// 	},
	// 	onLoad() {
	// 		let that=this;
	// 		uniCloud.callFunction({
	// 			name: 'list',
	// 			success(re){
	// 				// alert(JSON.stringify(re.result));
	// 				that.arr = re.result;
	// 			}
	// 		});
	// 	},
	// 	methods: {
	// 		add(){
	// 			let that=this;
	// 			uniCloud.callFunction({
	// 				name: 'add',
	// 				data:{
	// 					stu:{name:this.nm}
	// 				},
	// 				success(re){
	// 					//alert(JSON.stringify(re.result));
	// 					location.reload();
	// 				}
	// 			});
	// 		},
	// 		select(){
	// 			uniCloud.callFunction({
	// 				name: 'select',
	// 				data:{
	// 					stu:{name:this.cx},
	// 				},
	// 				success(re){
	// 					alert(JSON.stringify(re.result));
	// 					// location.reload();
	// 				}
	// 			});
	// 		}
	// 	}
	// }
